package com.example.version.controll.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.IOUtils;

import java.io.*;

@Slf4j
public class CommandUtil {

    /**
     * 执行 inux/cmd 命令
     *
     * @param command 命令
     * @return
     */
    public static boolean executeCommand(String command) {
        return executeCommand(command, null);
    }

    /**
     * 指定目录执行 linux/cmd 命令
     *
     * @param command 命令
     * @param file    目录
     * @return
     */
    public static boolean executeCommand(String command, File file) {
        BufferedReader reader = null;
        InputStreamReader inputStreamReader = null;
        Process p;
        try {
            //判断是操作系统是linux还是windows
//            String[] comds;
//            if (System.getProperties().get("os.name").toString().toUpperCase().indexOf("WINDOWS") >= 0) {
//                log.info("当前操作系统：windows");
//                comds = new String[]{"cmd", "/c", command};
//            } else {
//                log.info("当前操作系统：linux");
//                comds = new String[]{"/bin/sh", "-c", command};
//            }

            // 开始执行命令
            log.info("执行命令：" + command);
//            if (file!=null) {
//                p = Runtime.getRuntime().exec(comds, null, file);
//            } else {
                p = Runtime.getRuntime().exec(command);
//            }

            //开启线程监听（此处解决 waitFor() 阻塞/锁死 问题）
            new RunThread(p.getInputStream(), "INFO").start();
            new RunThread(p.getErrorStream(), "ERROR").start();
            int flag = p.waitFor();

            return true;
        } catch (IOException e) {
            log.error("Proto2Html 执行命令IO异常！", e);
            return false;
        } catch (InterruptedException e) {
            log.error("Proto2Html 执行命令中断异常！", e);
            return false;
        } catch (Exception e) {
            log.error("Proto2Html 执行命令出现异常！", e);
            return false;
        } finally {
            IOUtils.closeQuietly(reader);
            IOUtils.closeQuietly(inputStreamReader);
        }
    }
}

/**
 * 监听线程
 */
@Slf4j
class RunThread extends Thread {
    InputStream is;
    String printType;

    RunThread(InputStream is, String printType) {
        this.is = is;
        this.printType = printType;
    }

    public void run() {
        try {
            InputStreamReader isr = new InputStreamReader(is, "GBK");
            BufferedReader br = new BufferedReader(isr);
            String line = null;
            while ((line = br.readLine())!=null){
                if (printType.equals("ERROR")) {
                    System.err.println(printType + " >> " + line);
                } else {
//                    System.out.println(printType + " >> " + line);
                }
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}
